package com.today.usercenter.ui.activities;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import com.today.usercenter.R;
import com.today.usercenter.ui.widgets.crop.ClipImageLayout;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

/**
 * 裁剪头像图片界面 (只针对头像使用,返回地方写死了头像地址)
 */
public class HeadImageCropActivity extends Activity implements View.OnClickListener {
    private ClipImageLayout clipImageLayout;
    private String path;
    private Bitmap bitmap;
    private TextView actionbar_finish;
    private TextView actionbar_back;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_crop_image);
        actionbar_back = (TextView) findViewById(R.id.actionbar_back);
        actionbar_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                HeadImageCropActivity.this.finish();
            }
        });
        path = getIntent().getStringExtra("imgpath");
        clipImageLayout = (ClipImageLayout) findViewById(R.id.imageView1);
        actionbar_finish = (TextView) findViewById(R.id.actionbar_finish);
        actionbar_finish.setOnClickListener(this);

        if (android.os.Build.MODEL.contains("Lenovo")) {
            BitmapFactory.Options opts = new BitmapFactory.Options();
            opts.inSampleSize = 20;
            FileInputStream input = null;
            try {
                input = new FileInputStream(path);
                bitmap = BitmapFactory.decodeStream(input, null, opts);
                input.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            bitmap = file2bitmap(path);
        }

        clipImageLayout.setBitmap(bitmap);

    }

    public static Bitmap file2bitmap(String path) {
        try {
            return revitionImageSizeHD(path, 1600);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static Bitmap revitionImageSizeHD(String picfile, int size)
            throws IOException {
        if (size <= 0) {
            throw new IllegalArgumentException("size must be greater than 0!");
        }
        int photoSizesOrg = 2 * size;
        FileInputStream input = new FileInputStream(picfile);
        final BitmapFactory.Options opts = new BitmapFactory.Options();
        opts.inJustDecodeBounds = true;
        BitmapFactory.decodeStream(input, null, opts);

        try {
            input.close();
        } catch (Exception e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        int rate = 0;
        for (int i = 0; ; i++) {
            if ((opts.outWidth >> i <= photoSizesOrg && (opts.outHeight >> i <= photoSizesOrg))) {
                rate = i;
                break;
            }
        }
        opts.inSampleSize = (int) Math.pow(2, rate);
        opts.inJustDecodeBounds = false;
        Bitmap temp = safeDecodeBimtapFile(picfile, opts);
        return temp;
    }

    public static Bitmap safeDecodeBimtapFile(String bmpFile,
                                              BitmapFactory.Options opts) {
        BitmapFactory.Options optsTmp = opts;
        if (optsTmp == null) {
            optsTmp = new BitmapFactory.Options();
            optsTmp.inSampleSize = 1;
        }

        Bitmap bmp = null;
        FileInputStream input = null;

        final int MAX_TRIAL = 5;
        for (int i = 0; i < MAX_TRIAL; ++i) {
            try {
                input = new FileInputStream(bmpFile);
                bmp = BitmapFactory.decodeStream(input, null, opts);

                int degree = readPictureDegree(bmpFile);
                if (degree != 0) {
                    Matrix matrix = new Matrix();
                    matrix.postRotate(degree);
                    bmp = Bitmap.createBitmap(bmp, 0, 0, bmp.getWidth(),
                            bmp.getHeight(), matrix, true);
                }
                try {
                    input.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                break;
            } catch (OutOfMemoryError e) {
                e.printStackTrace();
                optsTmp.inSampleSize *= 2;
                try {
                    input.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            } catch (FileNotFoundException e) {
                break;
            }
        }

        return bmp;
    }

    /**
     * 读取图片属性：旋转的角度
     * 图片绝对路径
     *
     * @return degree旋转的角度
     */
    public static int readPictureDegree(String path) {
        int degree = 0;
        try {
            ExifInterface exifInterface = new ExifInterface(path);
            int orientation = exifInterface.getAttributeInt(
                    ExifInterface.TAG_ORIENTATION,
                    ExifInterface.ORIENTATION_NORMAL);
            switch (orientation) {
                case ExifInterface.ORIENTATION_ROTATE_90:
                    degree = 90;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    degree = 180;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    degree = 270;
                    break;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return degree;
    }


    @Override
    protected void onDestroy() {
        clipImageLayout = null;
        if (bitmap != null) {
            bitmap.recycle();
            bitmap = null;
        }
        super.onDestroy();
    }

    @Override
    public void onClick(View v) {
        Intent intent = new Intent();
        intent.putExtra("imgpath", clipImageLayout.clip());
        setResult(RESULT_OK, intent);
        finish();
    }
}
